﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using BuyingSpree_HPV.Help;
using BuyingSpree_HPV.Model;
using BuyingSpree_HPV.View;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Threading;

namespace BuyingSpree_HPV.VM
{
    public class MainViewModel : ViewModelBase
    {

        #region 属性

        private ObservableCollection<VaccineList> gridModelList;

        public ObservableCollection<VaccineList> GridModelList
        {
            get { return gridModelList; }
            set { gridModelList = value; RaisePropertyChanged(); }
        }

        public List<Area> OmitLists { get; set; }
        private ObservableCollection<Area> _cityLists;
        /// <summary>
        /// 表单数据
        /// </summary>
        public ObservableCollection<Area> CityLists
        {
            get { return _cityLists; }
            set { _cityLists = value; RaisePropertyChanged(); }
        }

        private Area _selectOmit;
        public Area SelectOmit
        {
            get { return _selectOmit; }
            set
            {
                _selectOmit = value;
                RaisePropertyChanged();
            }
        }
        private string _logMsg = string.Empty;
        public string LogMsg
        {
            get { return _logMsg; }
            set
            {
                _logMsg = value;
                RaisePropertyChanged();
            }
        }

        #endregion


        private RelayCommand<string> _editCommand;

        public RelayCommand<string> EditCommand
        {
            get
            {
                if (_editCommand == null)
                    _editCommand = new RelayCommand<string>(t => Edit(t));
                return _editCommand;
            }
        }
        /// <summary>
        /// 操作
        /// </summary>
        /// <param name="type"></param>
        private void Edit(string type)
        {
            try
            {
                switch (type)
                {
                    //设置Cookie
                    case "1":
                        {
                            EditCookieView view = new EditCookieView();
                            EditCookieViewModel viewModel = new EditCookieViewModel();
                            view.DataContext = viewModel;
                            var d = Dialog.Show(view);
                            viewModel.CloseDialg += () =>
                            {
                                Config.HeaderConfig.cookies = viewModel.Cookie;
                                Config.HeaderConfig.tk = viewModel.Tk;
                                d.Close();
                            };
                            break;
                        }
                    //选择用户
                    case "2":
                        {
                            HttpService.hasAvailableConfig();
                            SelectUserView view = new SelectUserView();
                            SelectUserViewModel viewModel = new SelectUserViewModel();
                            viewModel.InitUi();
                            view.DataContext = viewModel;
                            var d = Dialog.Show(view);
                            viewModel.CloseDialg += () =>
                            {
                                d.Close();
                            };
                            break;
                        }
                    //刷新列表
                    case "3":
                        {
                            if (GridModelList.Count == 0)
                            {
                                GridModelList = new ObservableCollection<VaccineList>();
                                var members = HttpService.GetVaccineList();
                                if (members != null && members.Count != 0)
                                {
                                    members.ForEach((ary) =>
                                    {
                                        GridModelList.Add(ary);
                                    });

                                    List<VaccineList> allowList = GridModelList.Where(s => DateTime.Now.Subtract(s.startTime).TotalSeconds > 50).ToList();
                                    if (allowList.Count != 0)
                                    {
                                        registry = new FluentScheduler.Registry();
                                        registry.Schedule(() =>
                                        SecKillTime(allowList)).WithName("SecKillTime").ToRunNow().AndEvery(10).Seconds();// 每1分钟执行一次
                                        FluentScheduler.JobManager.Initialize(registry);
                                    }

                                }
                            }

                            break;
                        }
                    //开始
                    case "4":
                        {

                            //HttpService.hasAvailableConfig();
                            LogMsg = "开始秒杀\r\n";
                            queue = new Queue<string>();
                            for (int i = 1; i < 5000; i++)
                            {
                                queue.Enqueue(i.ToString());
                            }
                            List<VaccineList> allowList = GridModelList.Where(s => DateTime.Now.Subtract(s.startTime).TotalSeconds > 50).ToList();
                            if (allowList.Count == 0)
                            {
                                MessageBox.Show("抢购时间未到 请稍后");
                                return;
                            }
                            Task.Factory.StartNew(() => PrintQueue(allowList));
                            break;
                        }
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LoggerHelper.log.Info(DateTime.Now.ToString() + "异常-" + ex.StackTrace + "\r\n描述-" + ex.Message);
            }
        }



        public MainViewModel()
        {
            CityLists = new ObservableCollection<Area>();
            InitUi();
        }


        private void InitUi()
        {
            GridModelList = new ObservableCollection<VaccineList>();
            OmitLists = ParseUtil.GetAreas();
        }

        #region 抢购
        /// <summary>
        /// 队列
        /// </summary>
        private Queue<string> queue;

        /// <summary>
        /// 结果
        /// </summary>
        public bool retuest = true;
        /// <summary>
        /// 开启秒杀队列线程
        /// </summary>
        /// <param name="allowList">可以秒杀的商品信息</param>
        private void PrintQueue(List<VaccineList> allowList)
        {
            try
            {
                while (retuest)
                {
                    if (queue.Count > 0)
                    {
                        LogMsg += $"\r\n 发送请求-{queue.Dequeue()}";
                        foreach (var item in allowList)
                        {
                            Task.Run(() =>
                            {
                                try
                                {
                                    string orderId = HttpService.SecKill(item.Id, "1", Config.HeaderConfig.memberId.ToString(), Config.HeaderConfig.idCard);
                                    if (!string.IsNullOrWhiteSpace(orderId))
                                    {
                                        retuest = false;
                                        LogMsg = DateTime.Now + $"抢购成功({orderId})";
                                        return;
                                    }
                                    //如果离开始时间120秒后，抢不到则不再继续
                                    if (item.startTime.Subtract(DateTime.Now).TotalSeconds > 120)
                                    {
                                        retuest = false;
                                        LogMsg += DateTime.Now + $"抢购失败";
                                        return;
                                    }
                                    Task.Delay(200);
                                }
                                catch (Exception ex)
                                {
                                    LogMsg += "未知异常" + ex.Message;
                                    LoggerHelper.log.Info(DateTime.Now.ToString() + "异常-" + ex.StackTrace + "\r\n描述-" + ex.Message);
                                }
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.log.Info(DateTime.Now.ToString() + "异常-" + ex.StackTrace + "\r\n描述-" + ex.Message);
            }
        }

        int count = 1;

        private FluentScheduler.Registry registry;

        /// <summary>
        /// 定时检测
        /// </summary>
        /// <param name="allowList"></param>
        private void SecKillTime(List<VaccineList> allowList)
        {
            try
            {
                var localTime = DateTime.Now;
                LogMsg += localTime + $"第几次：{count++},抢购中--\r\n";
                foreach (var item in allowList)
                {
                    if (localTime.Subtract(item.startTime).TotalSeconds < 10)
                    {
                        Task.Run(() =>
                        {
                            try
                            {
                                LogMsg += DateTime.Now + $"第几次：{count++},抢购中--\r\n";
                                string orderId = HttpService.SecKill(item.Id, "1", Config.HeaderConfig.memberId.ToString(), Config.HeaderConfig.idCard);
                                if (!string.IsNullOrWhiteSpace(orderId))
                                {
                                    FluentScheduler.JobManager.RemoveJob("SecKillTime");
                                    LogMsg = DateTime.Now + $"抢购成功({orderId})";
                                    return;
                                }
                                //如果离开始时间120秒后，抢不到则不再继续
                                if (item.startTime.Subtract(DateTime.Now).TotalSeconds > 120)
                                {
                                    FluentScheduler.JobManager.RemoveJob("SecKillTime");
                                    LogMsg += DateTime.Now + $"抢购失败";
                                    return;
                                }
                                Task.Delay(200);
                            }
                            catch (Exception ex)
                            {
                                LogMsg += "未知异常" + ex.Message + "-\r\n";
                                LoggerHelper.log.Info(DateTime.Now.ToString() + "异常-" + ex.StackTrace + "\r\n描述-" + ex.Message);
                            }
                        });
                    }
                }

            }
            catch (Exception ex)
            {

            }
        }
        #endregion

    }
}
